<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	const AUTH_TYPE_DATABASE = 1;
	const AUTH_TYPE_FACEBOOK = 2;
	const AUTH_TYPE_ACTIVATION = 3;

	private $_id;

	/**
	 * Authenticates a user.
	 * @param integer $type the authentication type, defaults to database.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate($type = self::AUTH_TYPE_DATABASE)
	{
		switch ($type)
		{
			case self::AUTH_TYPE_ACTIVATION:
				/** @var User $user */
				$user = User::model()->find('name=?', array($this->username));

				if ($user===null)
					$this->errorCode = self::ERROR_USERNAME_INVALID;
				else
				{
					$this->_id = $user->id;
					$this->username = $user->name;
					$this->setState('isAdmin', $user->admin);
					$this->errorCode = self::ERROR_NONE;
				}

				break;

			// Facebook authentication
			case self::AUTH_TYPE_FACEBOOK:
				$user = Yii::app()->fb->loadUser();

				if ($user === null)
					$this->errorCode = self::ERROR_USERNAME_INVALID;
				else
				{
					$this->_id = $user->id;
					$this->username = $user->name;
					$this->setState('fbuid',$user->fbuid);
					$this->setState('isAdmin', $user->admin);
					$this->errorCode = self::ERROR_NONE;
				}

				break;

			// Default authentication (database)
			case self::AUTH_TYPE_DATABASE:
			default:
				/** @var User $user */
				$user = User::model()->find('LOWER(name)=? AND status=?',
						array(strtolower($this->username), User::STATUS_ACTIVATED));

				if ($user===null)
					$this->errorCode = self::ERROR_USERNAME_INVALID;
				else if (!$user->validatePassword($this->password))
					$this->errorCode = self::ERROR_PASSWORD_INVALID;
				else
				{
					$this->_id = $user->id;
					$this->username = $user->name;
					$this->setState('isAdmin', $user->admin);
					$this->errorCode = self::ERROR_NONE;
				}

				break;
		}

		return $this->errorCode == self::ERROR_NONE;
	}

	/**
	 * @return integer the ID of the user record
	 */
	public function getId()
	{
		return $this->_id;
	}
}
